package com.dao.impl;

import com.util.HibernateUtil;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;

import com.dao.SourceDAO;
import com.rev.Message;
import com.rev.Source;
import com.rev.SourceHome;
import com.rev.Sourcetype;
import com.rev.SourcetypeHome;
import com.rev.Target;

public class SourceDAOImpl implements SourceDAO{
	private SourceHome sh = new SourceHome(); 
	private SourcetypeHome sth = new SourcetypeHome();
	public boolean insert(Source source) {
		try {
			Session session = HibernateUtil.getSessionFactory().openSession();
			Transaction  transaction = session.beginTransaction();
			sth.attachDirty(source.getSourcetype());
			sh.attachDirty(source);
			transaction.commit();
			session.close();
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	public boolean update(Source source) {
		try {
			Session session = HibernateUtil.getSessionFactory().openSession();
			Transaction  transaction = session.beginTransaction();
			sh.attachDirty(source);
			transaction.commit();
			session.close();
			return true;
		} catch (Exception e) {
			// TODO: handle exception
		}
		return false;
	}

	public boolean delete(Source source) {
		try {
			Session session = HibernateUtil.getSessionFactory().openSession();
			Transaction  transaction = session.beginTransaction();
			
			sh.delete(source);
			transaction.commit();
			session.close();
			return true;
		} catch (Exception e) {
			// TODO: handle exception
		}
		return false;
	}

	public Source findById(int id) {
		try {
			Session session = HibernateUtil.getSessionFactory().openSession();
			session.beginTransaction();
			Source s = sh.findById(id);
			session.getTransaction().commit();
			session.close();
			return s;
		} catch (Exception e) {
			// TODO: handle exception
		}
		return null;
	}

	public List<Message> findMessages(Source source) {
		// TODO Auto-generated method stub
		return null;
	}
	
	public List<Source> findAll() {

		try {
			Session session = HibernateUtil.getSessionFactory().openSession();
			session.beginTransaction();
			List list = sh.findByExample(new Source());
			session.getTransaction().commit();
			session.close();
			return list;
		} catch (Exception e) {
		}
		return null;
	}

}
